package com.jweb.plugins.rpc.impl;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

import com.jweb.plugins.rpc.bean.RpcRequest;
import com.jweb.plugins.rpc.bean.RpcResponse;
import com.jweb.plugins.rpc.bean.Service;
import com.jweb.plugins.rpc.impl.handler.ServiceType;
import com.jweb.plugins.rpc.impl.iface.IAgreement;
import com.jweb.plugins.rpc.impl.iface.IWatcher;

public class AgreementFactory {

	public synchronized static boolean startServer(Map<String, Service> handler, String host, int port, Set<ServiceType> suport) throws Exception {
		for (ServiceType st : suport) {
			RpcProcess(st.getCls().newInstance(), handler, host, port);
		}
		return true;
	}

	public synchronized static RpcResponse startClient(RpcRequest request, String host, int port, ServiceType st) throws Exception {
		return st.getCls().newInstance().opClient(request, host, port);
	}

	/**
	 * 【启动服务】同步方法
	 */
	private static boolean RpcProcess(IAgreement agree, Map<String, Service> handler, String host, int port) throws Exception {
		final CountDownLatch latch = new CountDownLatch(1);
		agree.opServer(new IWatcher() {
			@Override
			public void process(boolean bo) {
				if (bo)
					latch.countDown();
			}
		}, handler, host, port);
		latch.await();
		return true;
	}
}
